import { Injectable, HttpException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { PostsEntity } from './posts.entity';

export interface PostsRo {
  list: PostsEntity[];
}

@Injectable()
export class PostsService {
  constructor(
    @InjectRepository(PostsEntity)
    private readonly postsRepository: Repository<PostsEntity>,
  ) {}

  // 创建文章
  async create(post: Partial<PostsEntity>): Promise<PostsEntity> {
    const { title } = post;
    if (!title) {
      throw new HttpException('缺少文章标题', 401);
    }
    const doc = await this.postsRepository.findOne({ where: { title } });
    if (doc) {
      throw new HttpException('文章已存在', 401);
    }
    return await this.postsRepository.save(post);
  }

  // 获取文章列表
  async findAll(query): Promise<PostsRo> {
    const { id } = query;
    let posts = [];
    if (id) {
      posts = await this.postsRepository.find({ where: { id: id } });
    } else {
      posts = await this.postsRepository.find({ where: {} });
    }

    return { list: posts };
  }

  // 获取指定文章
  async findById(id): Promise<PostsEntity> {
    return await this.postsRepository.findOne({ where: { id: id } });
  }

  // 更新文章
  async updateById(post): Promise<PostsEntity> {
    const { id, ...params } = post;

    const existPost = await this.postsRepository.findOne({ where: { id: id } });
    if (!existPost) {
      throw new HttpException(`id为${id}的文章不存在`, 401);
    }
    const updatePost = this.postsRepository.merge(existPost, params);
    return this.postsRepository.save(updatePost);
  }

  // 刪除文章
  async remove(id): Promise<PostsEntity> {
    const existPost = await this.postsRepository.findOne({ where: { id: id } });

    if (!existPost) {
      throw new HttpException(`id为${id}的文章不存在`, 401);
    }
    return await this.postsRepository.remove(existPost);
  }
}
